<template>
  <div class="box">
    <div class="plotting" @click="plottingToView">标绘</div>
    <div class="emergency" @click="emergencyToView">应急服务信息</div>
    <Transition name="slide-left">
      <div class="plotting-content" v-if="plottingFlag">
        <div class="header">
          <span>标绘</span>
          <span class="close" @click="plottingToView"></span>
        </div>
        <div class="content-list">
          <div
            :class="['item', activeArr === index ? 'active' : '']"
            v-for="(item, index) in markData"
            :key="item"
            @click="toDialog(item, index)"
          >
            <span class="showorhide" @click.stop="controlEntity(index)">
              <img
                :src="item.hidden ? '/static/assets/3d/show.png' : '/static/assets/3d/hide.png'"
                alt=""
                srcset=""
              />
            </span>
            <span class="icon">
              <img :src="item.markStyle.img || '/static/icon/poi.png'" alt=""
            /></span>
            <span class="text">{{ item.markName }}</span>
            <span class="title">{{ item.markType === '文字' ? '字' : item.markType }}</span>
          </div>
        </div>
      </div>
    </Transition>
    <Transition name="slide-left">
      <div :class="['emergency-content']" :id="screenFlag ? 'screens' : ''" v-show="emergencyFlag">
        <div class="header">
          <div class="title">应急服务信息</div>
          <div class="ptr">
            <span class="screen" @click="openScreen"></span>
            <span class="close" @click="emergencyToView"></span>
          </div>
        </div>
        <div class="content-list">
          <el-table
            border
            :data="tableData"
            :show-header="false"
            @contextmenu="tableContextMenu"
            :style="{ width: '100%', maxHeight: '100%', overFlow: 'auto', fontSize: fs + 'px' }"
          >
            <el-table-column prop="name" width="100" />
            <el-table-column prop="data">
              <template #default="scope">
                <div v-html="scope.row.data"></div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </Transition>

    <div class="pt" ref="marklog" v-if="dialogVisible">
      <autoDialog
        :dialogVisible="dialogVisible"
        :title="markInfo.markName"
        @close="closeFeatureDialog"
        style="position: relative"
      >
        <template #header>
          <div> {{ markInfo.createTime }}</div>
        </template>
        <div class="box">
          <template v-if="markInfo.markFiles">
            <el-carousel
              height="180px"
              style="margin-bottom: 15px"
              v-if="markInfo.markFiles.length > 0"
            >
              <el-carousel-item v-for="(item, index) in markInfo.markFiles" :key="item.id">
                <template v-if="isVideoOrImageByExtension(item.fileType) == 'image'">
                  <div
                    class="carousImg"
                    @click="toViewImg(item.fileName, index)"
                    style="
                      width: 100%;
                      height: 100%;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <img
                      :src="imgArr[index]"
                      alt=""
                      style="max-width: 100%; max-height: 100%; object-fit: contain"
                    />
                  </div>
                </template>
                <template v-if="isVideoOrImageByExtension(item.fileType) === 'video'">
                  <div
                    class="carousVideo"
                    @click="toViewVideo(item.fileName, index)"
                    style="width: 100%; height: 100%"
                  >
                    <video controls width="100%" height="100%" muted :src="imgArr[index]"> </video>
                  </div>
                </template>
              </el-carousel-item>
            </el-carousel>
          </template>
          <template v-else>
            <div> 暂无数据 </div>
          </template>
          <p v-if="markInfo.markType == '点'">
            <span>经度:&nbsp;</span>{{ markInfo.entity.point.lng }}<span></span>
            <span style="margin-left: 20px"> 纬度:&nbsp;</span>{{ markInfo.entity.point.lat
            }}<span></span
          ></p>
          <br />
          <p v-if="markInfo.markMemo" style="margin-bottom: 15px">描述：{{ markInfo.markMemo }}</p>
          <hr />
          <ul
            class="btn-c"
            style="width: 100%; height: 100%; margin-top: 15px; justify-content: space-around"
          >
            <point-edit
              :key="markInfo.id"
              :markInfo="markInfo"
              v-if="markInfo.markType == '点'"
              @delEntity="delEntity"
              :imgAndVideoArr="originData"
              @updateData="updateData"
              @updateMarkData="updateMarkData"
            />
            <line-edit
              :key="markInfo.id"
              :markInfo="markInfo"
              v-if="markInfo.markType == '线'"
              @delEntity="delEntity"
              :imgAndVideoArr="originData"
              @updateData="updateData"
            />
            <area-edit
              :key="markInfo.id"
              :markInfo="markInfo"
              v-if="markInfo.markType == '面'"
              @delEntity="delEntity"
              :imgAndVideoArr="originData"
              @updateData="updateData"
            />
            <text-edit
              :key="markInfo.id"
              :markInfo="markInfo"
              v-if="markInfo.markType == '文字'"
              @delEntity="delEntity"
              :imgAndVideoArr="originData"
              @updateData="updateData"
            />
          </ul>
        </div>
      </autoDialog>
    </div>
  </div>

  <teleport to="body">
    <div class="image-video-container" v-if="overlay" @click="closeOverlay">
      <img :src="imageUrl" v-if="imageUrl" @click="toggleFullscreen" alt="Sample Image" />
      <video v-if="videoUrl" :src="videoUrl" controls></video>
    </div>
  </teleport>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, shallowRef, onMounted, inject } from 'vue'
import { getSysmMapMark, deleteSysmMapMark, deleteSysmMapMarkFile } from '../../../api/sysmapmark'
import { useMapStoreStore } from '../../../stores/index'
import { useRoute, useRouter } from 'vue-router'
// import '@wangeditor/editor/dist/css/style.css' // 引入 css
// import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import pointEdit from './components/pointEdit.vue'
import lineEdit from './components/lineEdit.vue'
import areaEdit from './components/areaEdit.vue'
import textEdit from './components/textEdit.vue'
import { getEmergencyServeInfos } from '../../../api/bigscreen'
import { createPointAndToView, createPopupNoView } from '../../../api/gis3d/maputils'
import { getViewmarfile } from '../../../api/bookmark'
import {
  createPopup,
  createLineMark as createLine,
  createCricleLineMark
} from '../../../api/gis3d/maputils'
import { options_mark } from '../../js/test'

const route = useRoute()
const store = useMapStoreStore()

const activeIndex = ref(-1)
const dialogVisible = ref(false)
const plottingFlag = ref(false)
const emergencyFlag = ref(false)
const plottingToView = () => {
  plottingFlag.value = !plottingFlag.value
  emergencyFlag.value = false
}

const imgArr = ref([])
const originData = ref([])

const getImg = async (name, index) => {
  const params = {
    fileName: name
  }
  let a = await getViewmarfile(params)
  const blobUrl = URL.createObjectURL(a)
  imgArr.value[index] = blobUrl
  originData.value[index] = a
}

const emergencyToView = () => {
  emergencyFlag.value = !emergencyFlag.value
  plottingFlag.value = false
}

const activeArr = ref(-1)
const entityALL = []
const markInfo = ref({})
const marklog = ref(null)
const toDialog = (e, indexs) => {
  // var index = activeArr.value.indexOf(e.id)
  // var arr = map3d.getAllMarks()
  // if (index > -1) {
  //   entityALL[index].entity.destroy()
  //   activeArr.value.splice(index, 1)
  //   entityALL.splice(index, 1)

  //   if (markInfo.value.id === e.id) {
  //     dialogVisible.value = false
  //     markInfo.value = {}
  //     imgArr.value = []
  //   }

  //   return
  // }

  activeArr.value = indexs
  var nowEntity = entityALL[indexs].entity
  var position = nowEntity.options.positions
    ? nowEntity.options.positions[0]
    : nowEntity.options.position
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(position[0], position[1], 20000),
    duration: 1 // 飞行时间（s）
  })

  markInfo.value = markData.value[indexs]
  markInfo.value.markType = nowEntity.options.attr.marktypes
  markInfo.value.entity = nowEntity
  dialogVisible.value = true
  console.log(markInfo)

  var index = 0
  for (const element of markInfo.value.markFiles) {
    getImg(element.fileName, index)
    index++
  }
}

const loadAllEntity = () => {
  var index = 0
  // entityALL = [];
  for (const item of markData.value) {
    map3d.drawMarkBydata(JSON.stringify(item.markExt))
    // activeArr.value.push(item.id)
    var entity = map3d.getAllMarks()
    var end = entity[entity.length - 1]
    end.options.attr.index = index
    end.options.attr.sid = item.id
    entityALL.push({ id: item.id, entity: end, index: index })
    index++
  }
}

const controlEntity = (index) => {
  var hidden = markData.value[index].hidden
  if (hidden) {
    markData.value[index].hidden = false
    entityALL[index].entity.show = false
    return
  }
  markData.value[index].hidden = true
  entityALL[index].entity.show = true
}

const switchType = (type, s, e) => {
  // initPopup()
  switch (type) {
    case '点':
      createPointMark(s, e)
      break
    case '线':
      createLineMark(s, e)
      break
    case '面':
      createAreaMark(s, e)
      break
    case '文字':
      createTextMark(s, e)
      break
    default:
      break
  }
}

const getData = (type, data, entity, index) => {
  markInfo.value = data
  markInfo.value.markType = type
  markInfo.value.entity = entity
  dialogVisible.value = true
  activeArr.value = index
  var index = 0
  for (const element of markInfo.value.markFiles) {
    getImg(element.fileName, index)
    index++
  }
}

const getEvent = (item) => {
  if (item.options.attr.marktype == 'mark-poi') {
    const index = markData.value.findIndex((obj) => obj.id === item.options.attr.sid)
    if (index === -1) {
      return
    }
    getData(
      item.options.attr.marktypes || '点',
      markData.value[index],
      entityALL[index].entity,
      index
    )
  }
}
onMounted(() => {
  viewEvent.on('nowMarkItem', getEvent)
})

onUnmounted(() => {
  viewEvent.off('nowMarkItem', getEvent)
})

const delEntity = () => {
  const index = markData.value.findIndex((obj) => obj.id === markInfo.value.entity.options.attr.sid)
  activeArr.value = -1
  markInfo.value.entity.destroy()
  entityALL.splice(index, 1)
  markData.value.splice(index, 1)
  markInfo.value = {}
  dialogVisible.value = false
}

const isFullscreen = ref(false)
const imageUrl = ref('')
const videoUrl = ref('')
const isVideoVisible = ref(false)
const overlay = ref(false)
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  isVideoVisible.value = false
}

const showVideo = () => {
  isVideoVisible.value = true
}
const toViewImg = (e, index) => {
  overlay.value = true
  imageUrl.value = imgArr.value[index]
}
const toViewVideo = (e, index) => {
  overlay.value = true
  videoUrl.value = imgArr.value[index]
}
const closeOverlay = () => {
  overlay.value = false
  videoUrl.value = ''
  imageUrl.value = ''
}
//改变文本字体大小
const fs = computed(() => {
  return screenFlag.value ? 35 : 18
})

const tableData = ref([
  {
    name: '灾情',
    data: `<div>青海：青海省启动2级响应，门源县震感强烈，个别房屋出现裂缝，暂未收到人员亡报告。
甘肃：暂未收到人员伤亡报告。
部救灾司：青海省门源县县城没有房屋倒塌，个别房屋受损，暂无人员伤亡报告。甘肃省永昌县暂、民乐县暂无人员伤亡报告。
宁夏：银川有震感。</div>`
  },
  {
    name: '处置行动',
    data: `地震系统共派出82人队伍赴现场。

青海：门源台距震中约37公里。省局已派出***副局长带队 22人携带4套仪器赶往现场。震前已与应急厅在全省进行提前部署。

       5点20分到达门源县城。

       6点25分***局长陪同省领导赶赴震区。

甘肃：***副局长带队19人携带8套仅器赶赴震区，张掖中心站4人已到达张`
  },
  {
    name: '快速评估',
    data: `会商结论:走滑型地震。原震区和祁连危险区近几日存在发生***级地震可能。震中八度设防，最高10度可达九度，10公里范围内平均3600米。可能造成数十人伤亡。震中距离最近的水库暂时无影响。`
  }
])

const initTbaleData = () => {
  getEmergencyServeInfos({
    earthQuakeId: store.eqid,
    earthQuakeType: store.earthquakeInfo.earthquakeType
  }).then((e) => {
    tableData.value[0].data = e.disasterSituation || '无'
    tableData.value[1].data = e.action || '无'
    tableData.value[2].data = e.rapidAssess || '无'
  })
}
const screenFlag = ref(false)
const openScreen = () => {
  screenFlag.value = !screenFlag.value
}

const markData = ref([])
const initData = () => {
  var data = {
    eqid: store.eqid
  }
  getSysmMapMark(data).then((e) => {
    e.forEach((item) => {
      item.hidden = true
      item.markStyle = JSON.parse(item.markStyle) || { img: '/static/icon/poi.png' }
    })
    markData.value = e
    loadAllEntity()
  })
}

const updateData = (type) => {
  var data = {
    eqid: store.eqid
  }
  getSysmMapMark(data).then((e) => {
    var nowinfo = e.filter((e) => e.id == markInfo.value.id)
    const index = markData.value.findIndex(
      (obj) => obj.id === markInfo.value.entity.options.attr.sid
    )
    markInfo.value.markFiles = nowinfo[0].markFiles
    var endFiles = markInfo.value.markFiles[markInfo.value.markFiles.length - 1]
    var index1 = markInfo.value.markFiles.length - 1
    var hidden = markData.value[index].hidden
    markData.value[index] = nowinfo[0]
    markData.value[index].hidden = hidden
    getImg(endFiles.fileName, index1)
  })
}

const updateMarkData = (info) => {
  var data = {
    eqid: store.eqid
  }
  getSysmMapMark(data).then((e) => {
    if (info == 'endActive') {
      let newE = e.slice(markData.value.length)
      var index = markData.value.length - 1
      for (const item of newE) {
        map3d.drawMarkBydata(JSON.stringify(item.markExt))
        var entity = map3d.getAllMarks()
        var end = entity[entity.length - 1]
        end.options.attr.index = index
        end.options.attr.sid = item.id
        entityALL.push({ id: item.id, entity: end, index: index })
        item.markStyle = JSON.parse(item.markStyle) || '/static/icon/poi.png'
        item.hidden = true
        markData.value.push(item)
        index++
      }
      return
    }
    var end = e[e.length - 1]
    map3d.drawMarkBydata(end.markExt)
    end.hidden = true
    // activeArr.value.push(end.id)
    var entity = map3d.getAllMarks()
    entity[entity.length - 1].options.attr.index = e.length - 1
    entity[entity.length - 1].options.attr.sid = end.id
    entityALL.push({ id: end.id, entity: entity[entity.length - 1] })
    end.markStyle = JSON.parse(end.markStyle) || '/static/icon/poi.png'
    end.hidden = true
    markData.value.push(end)
  })
}

const closeFeatureDialog = () => {
  dialogVisible.value = false
  // hidePopup && hidePopup()
}

const typeofType = (e, s) => {
  switch (e) {
    case '点':
      return s.markStyle || '/static/assets/3d/dian-a.png'
    case '线':
      return JSON.parse(s.markStyle)?.img || '/static/assets/3d/xian-a.png'
    case '面':
      return JSON.parse(s.markStyle)?.img || '/static/assets/3d/mian-a.png'
    case '文字':
      return JSON.parse(s.markStyle)?.img || '/static/assets/3d/wz-a.png'

    default:
      return '/static/assets/3d/d.png'
  }
}

watch(
  () => store.markFlag,
  (newval) => {
    updateMarkData('endActive')
  }
)

function isVideoOrImageByExtension(fileType) {
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  const videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm']
  if (imageExtensions.includes(fileType)) {
    return 'image'
  } else if (videoExtensions.includes(fileType)) {
    return 'video'
  }
  return 'unknown'
}

onMounted(() => {
  initTbaleData()
  initData()
})
</script>

<style lang="scss" scoped>
.image-video-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9998;
  display: flex;
  align-items: center;
  justify-content: center;
  img,
  video {
    max-width: 75%;
    object-fit: contain;
  }
}
* {
  padding: 0;
  margin: 0;
}
.editor-container {
  position: absolute;
  top: 100px; /* Adjust as needed */
  left: 100px; /* Adjust as needed */
  width: 600px; /* Adjust as needed */
  border: 1px solid #ccc;
  background-color: #fff;
  z-index: 1000; /* Ensure it appears above other content */
}

.editor-container .w-e-toolbar {
  border-bottom: 1px solid #ccc;
}

.editor-container .w-e-text-container {
  height: 300px; /* Adjust as needed */
  overflow-y: auto;
}

.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.5s ease;
}
.slide-left-enter,
.slide-left-leave-to {
  transform: translateX(-100%); /* 平移出视线 */
  opacity: 0; /* 消失 */
}
:deep(.el-table .cell) {
  line-height: normal;
}
.pt {
  // display: none;
  position: relative;
  z-index: 99;

  position: fixed;
  left: 65px;
  top: 125px;
  width: 0;
  height: 0;
  .btn-c {
    display: flex;
    li {
      display: flex;
      cursor: pointer;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #83dcf9;
    }
  }
}
#screens {
  position: fixed;
  top: 10vh;
  left: 10vw;
  height: 80vh;
  width: 80vw;
}
.box {
  // position: relative;
}
.plotting,
.emergency {
  color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  cursor: pointer;
  justify-content: center;
  writing-mode: vertical-rl;
  font-size: 16px;
  letter-spacing: 5px;
  padding-left: 6px;
}
.plotting {
  position: absolute;
  top: 20px;
  left: 0;
  width: 53px;
  height: 138px;
  background-image: url(/static/assets/3d/mark.png);
  background-size: 100% 100%;
}
.emergency {
  position: absolute;
  top: 180px;
  left: 0;
  width: 53px;
  height: 247px;
  background-image: url(/static/assets/3d/mark.png);
  background-size: 100% 100%;
}
.plotting-content {
  width: 260px;
  border-radius: 8px;
  height: 440px;
  position: absolute;
  left: 65px;
  top: 34px;
  box-sizing: border-box;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  .header {
    height: 35px;
    display: flex;
    align-items: center;
    position: relative;
    justify-content: center;
    background: linear-gradient(90deg, #0d5787 0%, rgba(14, 83, 128, 0) 99%);
    font-size: 20px;
    letter-spacing: 0px;
    color: #ffffff;
    font-weight: bold;
    .screen {
      width: 30px;
      height: 100%;
      cursor: pointer;
    }
    .close {
      position: absolute;
      width: 40px;
      height: 30px;
      background-image: url(/static/assets/3d/open.png);
      background-size: contain;
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;
    }

    .close-hover {
      transform: rotate(360deg);
    }
  }
  .content-list {
    height: calc(100% - 35px);
    box-sizing: border-box;
    padding: 15px 10px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 6px;
      height: 8px;
    }
    &::-webkit-scrollbar-button {
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #01c2ff;
      cursor: pointer;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-corner {
      display: none;
    }
    &::-webkit-resizer {
      display: none;
    }
    .item {
      display: flex;
      align-items: center;
      color: #fff;
      // padding: 0 10px;
      box-sizing: border-box;
      cursor: pointer;
      height: 40px;
      font-size: 16px;
      border-bottom: 1px solid #0d5480;
      // &:hover {
      //   background-color: #0b8cbe85;
      // }
      .showorhide {
        margin-top: 5px;
        margin-right: 5px;
      }
      .icon {
        width: 20px;
        height: 20px;
        // background-image: url(/static/assets/3d/bz.png);
        // background-size: 100% 100%;
        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
      .text {
        margin-left: 10px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .title {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 12px;
        box-sizing: border-box;
        border: 1px solid #3b91eb;
        text-align: center;
      }
    }
  }
}
.emergency-content {
  width: 600px;
  border-radius: 8px;
  height: 500px;
  position: absolute;
  left: 65px;
  top: 210px;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  z-index: 99;
  .header {
    height: 35px;
    display: flex;
    align-items: center;
    position: relative;
    justify-content: center;
    background: linear-gradient(90deg, #0d5787 0%, rgba(14, 83, 128, 0) 99%);
    font-size: 20px;
    letter-spacing: 0px;
    color: #ffffff;
    font-weight: bold;
    .ptr {
      position: absolute;
      right: 0;
      top: 0;
      height: 100%;
      display: flex;
      align-items: center;
      .close {
        width: 40px;
        height: 30px;
        background-image: url(/static/assets/3d/open.png);
        background-size: contain;
        cursor: pointer;
      }
    }

    .screen {
      width: 20px;
      height: 20px;
      background-image: url(/static/assets/3d/screen.png);
      background-size: contain;
      background-repeat: no-repeat;
      cursor: pointer;
      margin-right: 20px;
    }
    .screen:hover {
      transform: scale(1.2);
    }
  }
  .content-list {
    padding: 10px;
    height: calc(100% - 35px);
    overflow: auto;
    box-sizing: border-box;
    &::-webkit-scrollbar {
      width: 6px;
      height: 8px;
    }
    &::-webkit-scrollbar-button {
      display: none;
    }
    &::-webkit-scrollbar-thumb {
      background: #01c2ff;
      cursor: pointer;
      border-radius: 4px;
    }
    &::-webkit-scrollbar-corner {
      display: none;
    }
    &::-webkit-resizer {
      display: none;
    }
  }
}
.el-table {
  background-color: transparent;
  font-size: 2vw;
  overflow: auto;
  color: #fff;
  --el-table-border-color: #b9eeff;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.1);
  --el-table-header-text-color: #ffffff;
}

.active {
  background-color: #0b8cbe85;
}
</style>